package com.liuxy.javautil;

import java.util.Collection;

import org.json.JSONArray;

public class ObjectUtil {
	private static final String TAG = "MyTools.ObjectUtil";
	
	public static boolean isEmpty(Object o) {
        if (o==null) {
            return true;
        }
        if (o instanceof CharSequence){
            return ((CharSequence) o).length()==0;
        }
        if (o instanceof Collection){
            return ((Collection<?>) o).isEmpty();
        }
        if (o.getClass().isArray()){
            return ((Object[]) o).length==0;
        }
        if (o instanceof JSONArray){
            return ((JSONArray) o).length()==0;
        }
        throw new RuntimeException(o.getClass()+" can not be support here.");
    }
    /**
     * compare two object
     * 
     * @param o
     * @param another
     * @return <ul>
     *         <li>if both are null, return true</li>
     *         <li>return o.{@link Object#equals(Object)}</li>
     *         </ul>
     */
    public static boolean isEquals(Object o, Object another) {
        return o == another || (o == null ? another == null : o.equals(another));
    }


    /**
     * compare two object
     * <ul>
     * <strong>About result</strong>
     * <li>if v1 > v2, return 1</li>
     * <li>if v1 = v2, return 0</li>
     * <li>if v1 < v2, return -1</li>
     * </ul>
     * <ul>
     * <strong>About rule</strong>
     * <li>if v1 is null, v2 is null, then return 0</li>
     * <li>if v1 is null, v2 is not null, then return -1</li>
     * <li>if v1 is not null, v2 is null, then return 1</li>
     * <li>return v1.{@link Comparable#compareTo(Object)}</li>
     * </ul>
     * 
     * @param v1
     * @param v2
     * @return
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static <V> int compare(V v1, V v2) {
        return v1 == null ? (v2 == null ? 0 : -1) : (v2 == null ? 1 : ((Comparable)v1).compareTo(v2));
    }
    
    private ObjectUtil(){
		/* cannot be instantiated */
		throw new UnsupportedOperationException(TAG+" cannot be instantiated");
	}
}
